import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../domain/entities/anime.dart';
import '../providers/anime_provider.dart';
import '../../core/utils/chinese_title_mapper.dart';

/// 分类详情页面
class CategoryDetailPage extends StatefulWidget {
  final String categoryName;
  final String categoryType; // 'genre', 'status', 'type'
  final dynamic categoryValue; // genreId (int), status (String), type (String)
  final IconData categoryIcon;
  final Color categoryColor;

  const CategoryDetailPage({
    super.key,
    required this.categoryName,
    required this.categoryType,
    required this.categoryValue,
    required this.categoryIcon,
    required this.categoryColor,
  });

  @override
  State<CategoryDetailPage> createState() => _CategoryDetailPageState();
}

class _CategoryDetailPageState extends State<CategoryDetailPage> {
  final List<Anime> _animeList = [];
  final ScrollController _scrollController = ScrollController();
  
  bool _isLoading = false;
  bool _hasError = false;
  bool _hasMoreData = true;
  String _errorMessage = '';
  int _currentPage = 1;
  
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    _loadAnimeData();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >= 
        _scrollController.position.maxScrollExtent - 100) {
      if (!_isLoading && _hasMoreData) {
        _loadMoreData();
      }
    }
  }

  Future<void> _loadAnimeData({bool refresh = false}) async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
      _hasError = false;
      if (refresh) {
        _currentPage = 1;
        _animeList.clear();
        _hasMoreData = true;
      }
    });

    try {
      final provider = Provider.of<AnimeProvider>(context, listen: false);
      List<Anime> newAnime = [];
      
      switch (widget.categoryType) {
        case 'filter':
          // 热门排序
          newAnime = await provider.getTopAnime(
            page: _currentPage,
            filter: widget.categoryValue as String,
            limit: 20,
          );
          break;
        case 'genre':
          newAnime = await provider.getAnimeByGenre(
            genreId: widget.categoryValue as int,
            page: _currentPage,
            limit: 20,
          );
          break;
        case 'status':
          newAnime = await provider.getAnimeByStatus(
            status: widget.categoryValue as String,
            page: _currentPage,
            limit: 20,
          );
          break;
        case 'type':
          newAnime = await provider.getAnimeByType(
            type: widget.categoryValue as String,
            page: _currentPage,
            limit: 20,
          );
          break;
      }

      setState(() {
        if (refresh) {
          _animeList.clear();
        }
        _animeList.addAll(newAnime);
        _hasMoreData = newAnime.length >= 20;
        _isLoading = false;
        
        // 调试信息
        print('分类加载完成：');
        print('- 分类: ${widget.categoryName}');
        print('- 页码: $_currentPage');
        print('- 本次加载: ${newAnime.length} 个');
        print('- 总计: ${_animeList.length} 个');
        print('- 是否还有更多: $_hasMoreData');
      });
    } catch (e) {
      setState(() {
        _hasError = true;
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  Future<void> _loadMoreData() async {
    _currentPage++;
    await _loadAnimeData();
  }

  Future<void> _onRefresh() async {
    await _loadAnimeData(refresh: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: AppBar(
        title: Row(
          children: [
            Icon(widget.categoryIcon, color: widget.categoryColor),
            const SizedBox(width: 8),
            Text(widget.categoryName),
          ],
        ),
        backgroundColor: Colors.white,
        elevation: 0,
        shadowColor: Colors.black.withValues(alpha: 0.1),
      ),
      body: RefreshIndicator(
        onRefresh: _onRefresh,
        child: _buildBody(),
      ),
    );
  }

  Widget _buildBody() {
    if (_isLoading && _animeList.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_hasError && _animeList.isEmpty) {
      return _buildError();
    }

    if (_animeList.isEmpty) {
      return const Center(
        child: Text('该分类下暂无动漫数据'),
      );
    }

    return CustomScrollView(
      controller: _scrollController,
      slivers: [
        // 分类信息头部
        SliverToBoxAdapter(
          child: Container(
            margin: const EdgeInsets.all(16),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  widget.categoryColor.withValues(alpha: 0.8),
                  widget.categoryColor.withValues(alpha: 0.6),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Row(
              children: [
                Icon(
                  widget.categoryIcon, 
                  color: Colors.white, 
                  size: 32,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.categoryName,
                        style: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '已找到 ${_animeList.length} 部动漫',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.white.withValues(alpha: 0.9),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),

        // 动漫网格列表
        SliverPadding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          sliver: SliverGrid(
            gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
              maxCrossAxisExtent: 200,
              crossAxisSpacing: 12,
              mainAxisSpacing: 12,
              childAspectRatio: 0.75,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                final anime = _animeList[index];
                return _buildAnimeCard(anime);
              },
              childCount: _animeList.length,
            ),
          ),
        ),

        // 加载更多指示器
        if (_isLoading && _animeList.isNotEmpty)
          SliverToBoxAdapter(
            child: Container(
              padding: const EdgeInsets.all(16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    '正在加载更多动漫...',
                    style: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
          ),

        // 无更多数据提示
        if (!_hasMoreData && _animeList.isNotEmpty)
          SliverToBoxAdapter(
            child: Container(
              padding: const EdgeInsets.all(16),
              child: Column(
                children: [
                  Icon(
                    Icons.check_circle_outline,
                    color: Colors.grey[400],
                    size: 32,
                  ),
                  const SizedBox(height: 8),
                  Text(
                    '已显示所有${widget.categoryName}动漫',
                    style: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
            ),
          ),

        const SliverToBoxAdapter(child: SizedBox(height: 20)),
      ],
    );
  }

  Widget _buildAnimeCard(Anime anime) {
    final chineseTitle = ChineseTitleMapper.getBestChineseTitle(
      title: anime.title,
      titleJapanese: anime.titleJapanese,
      titleEnglish: anime.titleEnglish,
      titleSynonyms: anime.titleSynonyms,
    );
    final chineseGenres = ChineseTitleMapper.getChineseGenres(anime.genres);

    return Card(
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10),
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(10),
        onTap: () {
          Navigator.pushNamed(
            context,
            '/detail',
            arguments: {'id': anime.id},
          );
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 动漫封面
            Expanded(
              flex: 5,
              child: Stack(
                children: [
                  ClipRRect(
                    borderRadius: const BorderRadius.vertical(
                      top: Radius.circular(10),
                    ),
                    child: anime.imageUrl.isNotEmpty
                        ? Image.network(
                            anime.imageUrl,
                            width: double.infinity,
                            height: double.infinity,
                            fit: BoxFit.cover,
                            errorBuilder: (context, error, stackTrace) {
                              return Container(
                                width: double.infinity,
                                height: double.infinity,
                                color: Colors.grey[300],
                                child: const Center(
                                  child: Icon(Icons.broken_image, size: 40),
                                ),
                              );
                            },
                          )
                        : Container(
                            width: double.infinity,
                            height: double.infinity,
                            color: Colors.grey[300],
                            child: const Center(
                              child: Icon(Icons.image, size: 40),
                            ),
                          ),
                  ),
                  
                  // 评分标签
                  if (anime.score > 0)
                    Positioned(
                      top: 6,
                      right: 6,
                      child: Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 5,
                          vertical: 2,
                        ),
                        decoration: BoxDecoration(
                          color: Colors.black.withValues(alpha: 0.7),
                          borderRadius: BorderRadius.circular(5),
                        ),
                        child: Text(
                          anime.score.toStringAsFixed(1),
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 11,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
            
            // 动漫信息
            Expanded(
              flex: 2,
              child: Container(
                padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      chineseTitle,
                      style: const TextStyle(
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                        color: Color(0xFF2C3E50),
                        height: 1.2,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    if (chineseGenres.isNotEmpty) ...[
                      const SizedBox(height: 4),
                      Expanded(
                        child: Text(
                          chineseGenres.take(2).join(' · '),
                          style: TextStyle(
                            fontSize: 10,
                            color: Colors.grey[600],
                            height: 1.1,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildError() {
    return Center(
      child: Container(
        margin: const EdgeInsets.all(16),
        child: Card(
          elevation: 2,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  Icons.error_outline,
                  size: 64,
                  color: Colors.grey[400],
                ),
                const SizedBox(height: 16),
                Text(
                  '加载失败',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  _errorMessage,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[500],
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 24),
                ElevatedButton.icon(
                  onPressed: () => _loadAnimeData(refresh: true),
                  icon: const Icon(Icons.refresh),
                  label: const Text('重试'),
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 24,
                      vertical: 12,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
} 